import {im_getMessageList} from '../../utils/tim_utils'

const app = getApp()

const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = false
innerAudioContext.src = ''//动态更改

Page({
  data:{
    userInfo:{},
    advisorInfo:{},
    created:'',
    messages:{},

    is_playing:false,
    playing_uuid:'',
    innerAudioContext:''
  },

  onLoad:function(options){
    //从上一页面record获取咨询相关基本信息
    var userInfo = app.globalData.userInfo
    var advisorInfo = JSON.parse(options.advisorInfoBean)
    var created = options.created
    this.setData({
      userInfo: userInfo,
      advisorInfo: advisorInfo,
      created: created
    })

    //初始化音频播放管理器
    this.setData({
      innerAudioContext: innerAudioContext
    })
    innerAudioContext.onPlay(() => {
      this.setData({
        is_playing:true,
      })
      console.log("========== innerAudioContext: play ==========")
    })
    innerAudioContext.onError((res) => {
      this.setData({is_playing:false})
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    innerAudioContext.onStop((res)=>{
      this.setData({
        is_playing:false,
        playing_uuid:''
      })
      console.log("========== innerAudioContext: stop ==========")
    })
    innerAudioContext.onEnded((res)=>{
      this.setData({
        is_playing:false,
        playing_uuid:''
      })
      console.log("========== innerAudioContext: end ==========")
    })
  },

  onReady:function(){
    // 页面渲染完成
  },

  onShow:function(){
    // 页面显示
        //初始化加载聊天记录相关事件的处理逻辑
        wx.event.on('conversationInit',()=>{//订阅初始化获取聊天记录
          im_getMessageList(this.data.advisorInfo.id);
        })
        wx.event.on('renderMsgList',(e,nextReqMessageID,isCompleted)=>{//订阅初始化获取聊天记录后渲染至页面
          let messages = this.data.messages
          messages = e
          this.setData({
            messages : messages,
          })
        })
    wx.event.emit('conversationInit')
  },

  imagePreview(e){
    var currentUrl = e.currentTarget.dataset.src
    wx.previewImage({
      current: currentUrl,
      urls: [currentUrl]
    })
  },

  playAudio(e){//点击语音消息
    if(!this.data.is_playing){//播放
      this.data.innerAudioContext.src=e.currentTarget.dataset.src
      this.data.innerAudioContext.play()
      this.setData({
        playing_uuid: e.currentTarget.dataset.uuid
      })
    }else{//取消播放
      this.data.innerAudioContext.stop()
    }
  },
})